package com.stephen.shirodemo.auth;

import com.stephen.shirodemo.entity.User;
import com.stephen.shirodemo.mapper.UserMapper;
import com.stephen.shirodemo.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: stephen
 * @create: 2020-03-11 13:35
 * @description:
 */
public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;


    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 从session中获取用户
        User user = (User) principalCollection.fromRealm(this.getClass().getName()).iterator().next();
        List<String> permissionList = new ArrayList<>();

        // 查询当前用户所有权限
        if (user != null) {
            permissionList = userMapper.selectPermissionsByUserId(user.getId());
        }

        // 查询用户角色
        List<String> roleNames = userMapper.selectRoleNamesByUserId(user.getId());

        // 注意,两个类名,一个是zation, 一个是cation
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 添加权限
        info.addStringPermissions(permissionList);
        // 添加角色
        info.addRoles(roleNames);
        return info;
    }

    // 认证登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        String username = usernamePasswordToken.getUsername();
        User user = userService.findByUsername(username);
        return new SimpleAuthenticationInfo(user, user.getPassword(),this.getClass().getName());
    }
}
